package com.cmy.framework_base.basics

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.annotation.ColorInt
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.cmy.framework_base.common.BaseStateView
import com.cmy.framework_base.common.UiState
import com.cmy.framework_base.common.loading.LoadDialogView
import com.cmy.framework_base.common.loadsir.EmptyCallback
import com.cmy.framework_base.common.loadsir.ErrorCallback
import com.cmy.framework_base.common.loadsir.LoadingCallback
import com.cmy.framework_utils.JumpPageUtils
import com.cmy.framework_utils.log.KLog
import com.cmy.framework_utils.toast.toast
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import com.permissionx.guolindev.PermissionX
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch

/**
 * @name:
 *  BasicsActivity
 * @package:
 *  com.cmy.framework_base.basics
 * @date:
 *  2023/2/1614:59
 * @author
 *    cmy
 * @description
 *  基础类，Activity中实现各类基础框架的中间件
 */
abstract class BasicsActivity : AppCompatActivity() , BaseStateView {


    /**
     * 主页面的对应Handler
     */
    protected val mHandler = Handler(Looper.getMainLooper())


    /**
     * 是否为第一次加载
     */
    private var isFirstLoad = true



    protected var savedInstanceState: Bundle? = null


    /**
     * 页面状态管理
     */
    private var mLoadService: LoadService<Any>? = null


    /**
     * 页面加载状态显示
     */
    private var mLoadDialogView: LoadDialogView? = null

    //-------------------------------需要实现的抽象方法--------------------------------------
    /**
     * 返回视图
     */
    protected abstract fun getContentView(): View?

    /**
     * 视图初始化
     */
    protected abstract fun initView(bundle: Bundle?)

    /**
     * 数据初始化
     */
    protected abstract fun initData()


    //--------------------------可重写实现对应UI逻辑方法------------------------


    /**
     * 总是需要重新加载
     */
    protected open fun alwaysNeedReload() {}

    /**
     * 提供子类方法 在设置布局之前
     */
    protected open fun setWindowConfigure() {}

    /**
     * 失败重试,重新加载事件
     */
    protected open fun onReloadClick() {}

    /**
     * 再次可见时，是否重新请求数据，默认为true
     */
    protected open fun isNeedReload() = true

    /**
     * 获取传递参数，通过Intent实现对应参数的获取
     */
    protected open fun doIntent(intent: Intent){
        intent.extras?.let {
            doBundle(it)
        }
    }

    /**
     * 获取Intent中对应Bundle数据，
     * （使用此方法时，请勿修改doIntent中的父类调用，否则会出现获取不到数据的问题）
     */
    protected open fun doBundle(bundle: Bundle){}

    //------------------------------继承方法的实现-------------------------

    override fun showContent() {
        mLoadService?.let {
            mHandler.post { it.showSuccess() }
        }
    }

    override fun showLoading() {
        mLoadService?.let {
            mHandler.post { it.showCallback(LoadingCallback::class.java) }
        }
    }

    override fun showEmpty() {
        mLoadService?.let {
            mHandler.post { it.showCallback(EmptyCallback::class.java) }
        }
    }

    override fun showFailure(message: String?) {
        mLoadService?.let {
            mHandler.post { it.showCallback(ErrorCallback::class.java) }
                message?.toast(this)
        }
    }


    //-------------------------------生命周期数据绑定--------------------------

    @SuppressLint("SourceLockedOrientationActivity")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.savedInstanceState = savedInstanceState
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        doIntent(intent)
        setWindowConfigure()
        setContentView(getContentView())
        initImmersionBar()
        initView(intent.extras)
    }


    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        intent?.let {
            doIntent(intent)
        }
    }


    override fun onResume() {
        super.onResume()
        alwaysNeedReload()
        if (isFirstLoad) {
            initData()
            isFirstLoad = false
        } else {
            if (isNeedReload()) {
                initData()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        clearDisposable()
    }

    //-----------------------------自定义已实现的方法----------------------------



    /**
     * 状态栏相关设置
     */
    open fun initImmersionBar(
        @ColorInt statusBarColor: Int = ContextCompat.getColor(
            this,
            com.cmy.framework.resources.R.color.color_999999
        ), isDarkFont: Boolean = false
    ) {

    }


    /**
     * 取消所有订阅，防止内存泄漏
     */
    private fun clearDisposable() {
        if (mLoadDialogView != null){
            mLoadDialogView!!.dismissLoadView()
            mLoadDialogView = null
        }
    }


    /**
     * 显示加载View
     */
    private fun showLoadView() {
        mLoadDialogView?.showLoadView()
    }

    /**
     * 关闭加载View
     */
    private fun dismissLoadView() {
        mLoadDialogView?.dismissLoadView()
    }

    /**
     * 延时关闭加载View
     */
    fun dismissLoadView(delay: Long) {
        mLoadDialogView?.dismissLoadView(delay)
    }

    /**
     * 延时关闭加载View后需要处理的事务
     */
    fun dismissDelayWith(delay: Long, runnable: Runnable?) {
        mLoadDialogView?.dismissDelayWith(delay,runnable)
    }

    /**
     * 请求权限
     */
    fun requestPermissions(vararg permissions: String, block: () -> Unit) {
        requestPermissions(listOf(*permissions), block)
    }


    private fun requestPermissions(permissions: List<String>, block: () -> Unit) {
        PermissionX.init(this)
            .permissions(permissions)
//            .onExplainRequestReason { scope, deniedList ->
//                val message = "PermissionX需要您同意以下权限才能正常使用"
//                scope.showRequestReasonDialog(deniedList, message, "Allow", "Deny")
//            }
            .request { allGranted, _, deniedList ->
                if (allGranted) {
                    block()
                } else {
                    "您拒绝了如下权限：$deniedList".toast(this)
                }
            }
    }


    /**
     * 注册LoadSir
     *
     * @param view
     *       替换视图（需要添加load变化的，才会对应的显示）
     */
    fun registerLoadSir(view: View) {
        mLoadService = LoadSir.getDefault().register(view) { onReloadClick() }
    }

    /**
     * 注册加载弹窗
     */
    fun registerLoadDialogView(loadDialogView: LoadDialogView){
        mLoadDialogView = loadDialogView
    }




    /**
     * 监听加载的UI用户界面状态
     */
    fun refreshUiState(uiState: MutableStateFlow<UiState>) {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                uiState.collect {
                    KLog.e("-------lifecycleScope.UiState = $it")
                    when (it) {
                        UiState.Loading -> showLoadView()
                        UiState.LoadEnd -> {
                            dismissLoadView()
                            showContent()
                        }
                        UiState.LoadError -> {
                            dismissLoadView()
                            showEmpty()
                        }
                        UiState.LoadComplete -> {
                            dismissLoadView()
                            showContent()
                        }
                        UiState.LoadDefault -> {}
                    }
                }
            }
        }
    }

    //--------------------------------




    /**
     * 跳转页面
     * @param clz    所跳转的目的Activity类
     * @param bundle 跳转所携带的信息
     */
    protected inline fun <reified T:Activity> startActivity(clz:T, bundle: Bundle? = null) {
        val intent = Intent(this, clz::class.java)
        if (bundle != null) {
            intent.putExtras(bundle)
        }
        startActivity(intent)
    }



    /**
     * 跳转页面
     * @param bundle 跳转所携带的信息
     */
    protected inline fun <reified T : Activity> startActivityBundle(block:Bundle.() -> Unit) {
        JumpPageUtils.startActivityBundle<T>(this,block)
    }


    /**
     * 页面跳转实现方案
     */
    protected inline fun <reified  T : BasicsActivity> startActivity(block:Intent.() -> Unit){
        JumpPageUtils.startActivity<T>(this,block)
    }

}